package cn.xiongxf.service.impl;

import cn.xiongxf.domain.CourseMarket;
import cn.xiongxf.domain.CourseUserLearn;
import cn.xiongxf.dto.PayResult2MQDTO;
import cn.xiongxf.mapper.CourseUserLearnMapper;
import cn.xiongxf.service.ICourseMarketService;
import cn.xiongxf.service.ICourseUserLearnService;
import cn.xiongxf.util.AssertUtil;
import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.mapper.EntityWrapper;
import com.baomidou.mybatisplus.service.impl.ServiceImpl;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang.time.DateUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.Date;
import java.util.List;
import java.util.Map;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author xiongxiaofu
 * @since 2022-08-16
 */
@Service
@Slf4j
@Transactional
public class CourseUserLearnServiceImpl extends ServiceImpl<CourseUserLearnMapper, CourseUserLearn> implements ICourseUserLearnService {
    @Autowired
    private ICourseMarketService courseMarketService;

    /**
     * 支付结果处理
     */
    @Override
    public void payResultHandler (PayResult2MQDTO dto){
        String orderNo = dto.getOrderNo();

        // 判断重复消费
        AssertUtil.isFalse(existByOrderNO(dto.getOrderNo()), "重复消费！");

        String extParams = dto.getExtParams();
        // 扩展参数非空校验
        AssertUtil.isNotEmpty(extParams, "扩展参数无效！");

        // // 解析扩展参数 {"loginId":3, "courseIds":[1, 2, 3, 4]}
        Map<String, Object> map = JSON.parseObject(extParams, Map.class);

        // 1.获取课程IDs和用户ID
        Long loginId = Long.valueOf(map.get("loginId").toString());
        // map.get("courseIds")是JSONArray格式
        List<Long> courseIds = JSON.parseArray(map.get("courseIds").toString(), Long.class);

        // 2.保存用户和课程的关系
        Date now = new Date();
        courseIds.forEach(courseId -> {
            // 是否已购买课程
            // 查询有效的购买记录
            CourseUserLearn courseUserLearn = selectOne(new EntityWrapper<CourseUserLearn>()
                    .eq("login_id", loginId)
                    .eq("course_id", courseId)
                    .eq("state", 0)  // 0已购买，1已过期
              );

            // 查询课程营销
            CourseMarket courseMarket = courseMarketService.selectById(courseId);

            if (courseUserLearn != null){
                // 累加有效时间
                Date endDate = DateUtils.addDays(courseUserLearn.getEndTime(), courseMarket.getValidDays());
                courseUserLearn.setEndTime(endDate);
                courseUserLearn.setCourseOrderNo(dto.getOrderNo());
                // 更新购买记录
                updateById(courseUserLearn);
            }else {
                // 结束时间
                Date endDate = DateUtils.addDays(now, courseMarket.getValidDays());
                courseUserLearn = new CourseUserLearn();
                courseUserLearn.setCourseId(courseId);
                courseUserLearn.setCourseOrderNo(dto.getOrderNo());
                courseUserLearn.setCreateTime(now);
                courseUserLearn.setStartTime(now);
                courseUserLearn.setEndTime(endDate);
                courseUserLearn.setLoginId(loginId);
                courseUserLearn.setState(0);  // 0已购买，1已过期

                // 新增购买记录
                insert(courseUserLearn);
                log.info("新增购买记录：{}", courseUserLearn);
            }
        });
    }

    // 抽取方法：根据订单号查询购买记录列表
    private boolean existByOrderNO(String orderNo) {
        List<CourseUserLearn> courseUserLearnList = selectList(new EntityWrapper<CourseUserLearn>().eq("course_order_no", orderNo));
        return courseUserLearnList.size() > 0;
    }
}
